// 引入http模块
import http from 'wechat-http'

// 配置请求的根路径
http.baseURL = 'https://live-api.itheima.net'

// 配置请求拦截器
http.intercept.request = (params) => {
  const token = getApp().token
  // 创建了一个默认的请求头对象
  const defualtHeader = {}
  if (token) defualtHeader.Authorization = token
  params.header = Object.assign({}, defualtHeader, params.header)
  return params
}

// 配置响应拦截器
http.intercept.response = async ({ statusCode, data, config }) => {
  if (statusCode === 401) {
    // 判断: 如果refreshToken也过期, 去登录页
    if (config.url.includes('/refreshToken')) {
      const stack = getCurrentPages()
      const currentPage = stack[stack.length - 1]
      const redirectURL = currentPage.route
      return wx.redirectTo({
        url: `/pages/login/index?redirectURL=/${redirectURL}`,
      })
    }

    const app = getApp()

    // 判断: 刷新token在一个大的前提-->必须有refreshToken
    if (!app.refreshToken) return

    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: app.refreshToken,
      },
    })
    if (res.data) {
      app.setToken(res.data.token, res.data.refreshToken)
      // 无感请求
      return http(
        Object.assign(config, {
          header: {
            Authorization: app.token,
          },
        })
      )
    }
  }
  return data
}

// 挂载到全局对象
wx.http = http

// 模块化导出
export default http
